package com.hp.bon.sgw.start;

import java.io.File;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.bean.SysParamBean;
import com.hp.bon.sgw.ctrl.ControllerConfigService;
import com.hp.bon.sgw.ctrl.PetriExecutor;
import com.hp.bon.sgw.ctrl.SGWProcessWatchDog;
import com.hp.bon.sgw.ctrl.SpringProgramerStarter;
import com.hp.bon.sgw.threads.ProcessLogCacheManager;
import com.hp.bon.sgw.util.Comutils;
import com.hp.bon.sgw.util.LogTool;

public class SGWControllerStarter {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger("LOCAL_FILE");

	private volatile boolean stopFlag = false;

	public void stop() {
		stopFlag = true;
	}
	public static final String startFlagKey = "startFlag";
	public void start(String[] args) {
		LogTool.installSLF4JBridge();
		String propFile = null;
		if (args.length > 0) {
			propFile = args[0];
		} else {
			propFile = "etc/sgw.properties";
		}

	
		String startFlag = "start-";
		for (String arg : args) {
			if (arg.startsWith(startFlag)) {
				String startVal = arg.substring(arg.length() - 1);
				System.out.println(startFlagKey + ":" + startVal);
				System.setProperty(startFlagKey, startVal);

			}
		}
		System.setProperty(startFlagKey, "o");

    String sgwHome = System.getProperty("SGW_HOME");
    if (sgwHome == null) {
      sgwHome = System.getenv("SGW_HOME");
    }
    String configFile = sgwHome + File.separator + "etc" + File.separator + "sysparams.conf";

    Map<String,SysParamBean> sysparamsMap = null;
    File confFile = new File(configFile);
    try {
      sysparamsMap = Comutils.loadSysParams(confFile);

      boolean hasInvalidParam = false;
      for (SysParamBean paramBean : sysparamsMap.values()) {
        if (!paramBean.validate()) {
          hasInvalidParam = true;
          logger.error("bad system param value for   " + paramBean.getName() + " cur value:" + paramBean.getValue() + " error code 169");
        }
      }
      if (hasInvalidParam) {
        System.out.print("quit program");
        System.exit(-2);
      }
    }
    catch (Exception e) {
      logger.error("read system param file err ,errcode 101 " + e.toString());
      System.out.print("quit program");
      System.exit(-1);
    }
    SysParamBean ifAutoActiveParm = (SysParamBean)sysparamsMap.get("other.if_auto_active");
    if ((ifAutoActiveParm != null) && (ifAutoActiveParm.getValue().equals("1")) && 
      ("v".equalsIgnoreCase(System.getProperty(startFlagKey)))) {
      System.out.println("auto active flag is true,chanage start flag to o");
      System.setProperty("startFlag", "o");
    }

    SysParamBean processCheckParm = (SysParamBean)sysparamsMap.get("other.check_process_time");
    String checkPeriod = "30";
    if (processCheckParm != null) {
      checkPeriod = processCheckParm.getValue();
    }

    System.setProperty("other.check_process_time", checkPeriod);

    ControllerConfigService.getInstance().init(propFile);

    String[] springXmls = { "spring-sgwcontroller.xml", "spring-base.xml" };
    SpringProgramerStarter starter = new SpringProgramerStarter() {
      PetriExecutor petriExecutor;
      SGWProcessWatchDog watchDog;

      public void runPeriodJob() {
        if (this.watchDog == null) {
          this.watchDog = ((SGWProcessWatchDog)this.ctx.getBean("sgwProcessWatchDog"));
        }
        this.watchDog.doShutdownCheck();
        this.watchDog.checkNodeStatus();
      }

      public boolean needStop()
      {
        if (this.petriExecutor == null) {
          this.petriExecutor = ((PetriExecutor)this.ctx.getBean("petriExecutor"));
        }
        return this.petriExecutor.needStop();
      }
    };
    starter.setHomeDirVar("SGW_HOME");
    starter.setStartPropertyFile(propFile);
    starter.setSpringFiles(springXmls);
    starter.start();
    SpringContext.setCtx(starter.ctx);

    ProcessLogCacheManager.getInstance().start();

    while ((!this.stopFlag) && (!starter.needStop())) {
      try {
        Thread.sleep(1000L);
        starter.runPeriodJob();
      } catch (InterruptedException e) {
        break;
      }
    }
    System.exit(0);
  }

  public static void main(String[] args) {
    new SGWControllerStarter().start(args);
  }
}